﻿using AutoMapper;
using MediatR;
using RBAC.Domain.Dto.Output;
using RBAC.Domain.RBAC;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.Permission;

namespace RBAC.Read.Api.Application.Handler.Permission
{
    public class GetPermissionListHandler : IRequestHandler<GetPermissionListCommand, APIPaging<PermissionDto>>
    {
        private readonly IBaseRepository<PermissionModel> permissionRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetPermissionListHandler> logger;

        public GetPermissionListHandler(IBaseRepository<PermissionModel> permissionRepository, IMapper mapper, ILogger<GetPermissionListHandler> logger)
        {
            this.permissionRepository = permissionRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIPaging<PermissionDto>> Handle(GetPermissionListCommand request, CancellationToken cancellationToken)
        {
            APIPaging<PermissionDto> res = new APIPaging<PermissionDto>();
            
            // 构建查询条件
            string whereClause = "";
            object parameters = new { }; // 默认空参数对象
            
            if (!string.IsNullOrEmpty(request.PermissionName))
            {
                whereClause = "PermissionName LIKE @PermissionName";
                parameters = new { PermissionName = $"%{request.PermissionName}%" };
            }

            // 使用Dapper分页查询
            var (data, totalCount) = permissionRepository.GetPaged(
                request.PageIndex, 
                request.PageSize, 
                whereClause, 
                "Id DESC", 
                parameters
            );

            res.PageDatas = mapper.Map<List<PermissionDto>>(data);
            res.TotalCount = totalCount;
            res.Code = APIEnums.Success;
            res.Msg = "获取权限列表成功";
            logger.LogInformation("获取权限列表成功");
            
            return Task.FromResult(res);
        }
    }
}
